package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
//@WebFilter("/*")
public class LoginCheckFilter implements Filter {
    //路径匹配器
    private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //获取本次请求的URI  localhost:8080/backend/index.html  contains  /backend/**不符合;contains /backend/index.html符合
        String requestURI = request.getRequestURI();
        //定义不需要拦截的资源
        String[] urls = {"/employee/login", "/employee/logout", "/backend/**", "/front/**"};
        //判断请求是否不需要拦截
        boolean check = check(requestURI, urls);
        if (check) {
            //本次请求不需要处理,放行
            filterChain.doFilter(request, response);
            return;
        }

        //需要处理,先判断是否登录
        Object emp = request.getSession().getAttribute("emp");
        if (emp != null) {
            log.info("用户{}已登录,id为",emp);
            //已经登录,放行
            filterChain.doFilter(request, response);
            return;
        }
        //未登录,返回对应的错误信息
        log.info("用户未登录");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }

    public boolean check(String url, String[] urls) {
        for (String s : urls) {
            boolean match = PATH_MATCHER.match(s, url);
            if (match) {
                return true;
            }
        }
        return false;
    }
}
